/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.customer;

import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.WidelyResourceDao;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * 广泛资源业务处理
 * @ClassName 〈WidelyResourceService>
 * @Author 朱永波
 * @Date 2017/11/7 18:39
 */
@Service
public class WidelyResourceService extends BaseService {

    @Resource
    private WidelyResourceDao widelyResourceDao;
    @Resource
    private ResourceImportRecordService resourceImportRecordService;
    @Resource
    private UserService userService;
    @Resource
    private CustomerService customerService;
    @Resource
    private NJCodeUtil njCodeUtil;


    /**
     * 根据id查询广泛资源
     * @param map
     *month: 查询表月份
     * widelyId: 广泛资源id
     * @return
     */
    public Map queryWidelyResourceById(Map map){
        return widelyResourceDao.queryWidelyResourceById(map);
    }

    /**
     * 回写转化商机id
     * @param map
     * widelyId：广泛资源id
     * busId：转化商机id
     * month：月份
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateWidelyResourceBusId(Map map){
        widelyResourceDao.updateWidelyResourceBusId(map);
    }

    /**
     * 广泛资源导入
     * @param rowsList
     * @param params
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> saveWidelyResourceBatch(List<List<String>> rowsList, Map params) {
        User user = (User) params.get("User");
        if(null == user){
            throw new BizException("导入失败！导入人信息不完整！", 10005);
        }
        String tableName = params.get("tableName").toString();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map queryParams = new HashMap();
        StringBuffer insert = new StringBuffer();
        Long recordId = resourceImportRecordService.saveWidelyResourceImportRecord(user, rowsList.size() - 1).getId();
        insert.append("INSERT INTO "+tableName+" (id, create_time, creater_id, creater_name, creater_org_id, import_time, import_record_id, importer_id, " +
                "importer_name, import_org_id, contact_way, customer_phone, name, remark, customer_phone_bak) VALUES");
        StringBuffer temp;
        StringBuffer insertTemp;
        rowsList.remove(0);
        String now = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
        List<List<List<String>>> arrList = createList(rowsList, 5000);
        String phone = null;
        String value = null;
        for (List<List<String>> rows : arrList) {
            insertTemp = new StringBuffer(insert);
            for (int i = 0; i < rows.size(); i++) {
                List<String> row = rows.get(i);
                temp = new StringBuffer("(" + keyWorker.nextId() + ",'" +DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "',"
                        + user.getId() + ",'" + user.getName() + "'," + user.getOrgId() + ",'" +now  + "'," + recordId + "," + user.getId() + ",'" + user.getName() + "'," + user.getOrgId() + ",'" + CustomerConstant.CUS_CONTACT_WAY_MOBILE + "',");
                phone = null;
                for (int j = 0; j < 3; j++) {
                    value = null;
                    if (j <= row.size() - 1) {
                        value = row.get(j);
                    }
                    value = StringUtils.removeSqlTag(value);
                    if (StringUtils.isNotEmpty(value != null ? value.trim() : null)) {
                        if(j == 0){
                            temp.append("'" + njCodeUtil.encrypt(value.trim().replace("-","")) + "'");
                            phone = value;
                        }else{
                            temp.append("'" + value + "'");
                        }
                    } else {
                        temp.append("''");
                    }
                    temp.append(",");
                    if (j == 2) {
                        temp.append("''");//2018-09-29去掉备份
                    }
                }
                if (temp.length() > 0) {
                    temp.append("),");
                }
                insertTemp.append(temp);
            }
            // 便于回收
            rows = null;
            queryParams.put("sql", insertTemp.toString().substring(0, insertTemp.length() - 1));
            widelyResourceDao.insertSql(queryParams);
        }
        return resultMap;
    }

    /**
     * 转化行列
     * @param targe
     * @param size
     * @return
     */
    private static List<List<List<String>>>  createList(List<List<String>> targe,int size) {
        List<List<List<String>>> listArr = new ArrayList();
        //获取被拆分的数组个数
        int arrSize = targe.size()%size==0?targe.size()/size:targe.size()/size+1;
        for(int i=0;i<arrSize;i++) {
            List<List<String>>  sub = new ArrayList();
            //把指定索引数据放入到list中
            for(int j=i*size;j<=size*(i+1)-1;j++) {
                if(j<=targe.size()-1) {
                    sub.add(targe.get(j));
                }
            }
            listArr.add(sub);
        }
        return listArr;
    }

    /**
     * 查询广泛资源列表
     * @param map
     * @return
     */
    public List<Map> queryWidelyResourceList(Map map){
        return widelyResourceDao.queryWidelyResourceList(map);
    }

    /**
     * 查询广泛资源实体列表
     * @param map
     * @return 实体
     */
    public List<Map> queryWidelyResourceEntityList(Map map){
        return widelyResourceDao.queryWidelyResourceEntityList(map);
    }

    /**
     * 查询广泛资源-count
     * @param map
     * @return
     */
    public Integer queryWidelyResourceCount(Map map){
        return widelyResourceDao.queryWidelyResourceCount(map);
    }


    /**
     * 分配广泛资源
     * @param map
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map updateWidelyResourceReceiver(Map map){
        if((null == map.get("ids") || StringUtils.isEmpty(map.get("ids").toString())) && (null == map.get("allotNum") || Integer.parseInt(map.get("allotNum").toString()) <= 0)){
            throw new BizException("分配失败！广泛资源获取失败！，", 10005);
        }
        if(null == map.get("User")){
            throw new BizException("分配失败！分配人信息不完整！，", 10005);
        }
        if(null == map.get("receiverId")){
            throw new BizException("分配失败！接收人信息不完整！，", 10005);
        }
        if(null == map.get("month")){
            throw new BizException("分配失败！查询月表不存在！，", 10005);
        }
//        List<Map> widelyResourceList = (List<Map>) map.get("widelyResourceList");
        User user = (User) map.get("User");
        User receiver = userService.getUserById(Long.parseLong(map.get("receiverId").toString()));
        Integer total = 0;
        int successNum = 0;
        Map params = new HashMap();
        Date now = new Date();
        String nowDate = DateUtil.dateToString(now, "yyyy-MM-dd HH:mm:ss");
        String month = map.get("month").toString();
        String ids = null != map.get("ids") && StringUtils.isNotEmpty(map.get("ids").toString()) ? map.get("ids").toString() : null;
        params.putAll(map);
        params.put("month", month);
        params.put("allotterId", user.getId());
        params.put("allotterName", user.getName() + user.getLoginName());
        params.put("allotTime", nowDate);
        params.put("receiverId", receiver.getId());
        params.put("receiverName", receiver.getName() + receiver.getLoginName());
        params.put("receiverOrgId", receiver.getOrgId());
        params.put("updateTime", nowDate);
        params.put("updaterId", user.getId());
        params.put("updaterName", user.getName() + user.getLoginName());
        params.put("updaterOrgId", user.getOrgId());
        if(null != map.get("allotNum")){
            total = Integer.parseInt(map.get("allotNum").toString());
            params.put("allotNum", total);
            successNum = widelyResourceDao.updateWidelyResource(params);
        }else if(StringUtils.isNotEmpty(ids)){
            total = ids.split(",").length;
            params.put("ids", ids);
            successNum = widelyResourceDao.updateWidelyResource(params);
        }
        map.put("total", total);
        map.put("succeed", successNum);
        map.put("failed", total - successNum);
//        String content = user.getName() + user.getLoginName() + "分配给" + receiver.getName() + receiver.getLoginName() + (widelyResourceList.size() - failedNum) + "条线索";
//        customerService.saveCustomerRecord(null, "", "cus_widely_resource_" + month, null, CustomerConstant.CUS_OPERATE_RES_ALLOT, user.getId(), content);
        return map;
    }

    /**
     * 工作台统计-广泛资源完成情况
     * @param map
     * @return
     */
    public Map queryCompleteSituation(Map map){
        String month = DateUtil.dateToString(new Date(), "yyyyMM");
        map.put("month", month);
        return widelyResourceDao.queryCompleteSituation(map);
    }

    /**
     * 线索拨打电话回写备注
     * @param user
     * @param id
     * @param month
     */
    public void updateWidelyResourceCall(User user, Long id, String month){
        Map map = new HashMap();
        map.put("id", id);
        map.put("lastFollowerId", user.getId());
        map.put("lastFollowerName", user.getName());
        map.put("lastFollowContent", "打电话");
        map.put("lastFollowTime", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        map.put("month", month);
        widelyResourceDao.updateWidelyResourceCall(map);
    }
}
